package com.defect.config;

import com.defect.filter.ImageCodeFilter;
import com.defect.service.securityService.securityServiceImpl.DecisionManager;
import com.defect.service.securityService.securityServiceImpl.SecurityMetadataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Configuration
public class Securityconfig extends WebSecurityConfigurerAdapter{
	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	@Autowired
	private ImageCodeFilter imageCodeFilter;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		SecurityMetadataSource sms = new SecurityMetadataSource();
		DecisionManager dm = new DecisionManager();

		http.headers().frameOptions().disable();
//		http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class)
		http.httpBasic().disable()
			.csrf().disable();
//			.authorizeRequests()
//				.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
//
//					@Override
//					public <O extends FilterSecurityInterceptor> O postProcess(O object) {
//						object.setSecurityMetadataSource(sms);
//						object.setAccessDecisionManager(dm);
//						return object;
//					}
//				})
//				.anyRequest().authenticated()
//				.and()
//			.formLogin()
//				.loginPage("/login.html")
//				.loginProcessingUrl("/login")
//				.successHandler(authenticationSuccessHandler)
//				.failureHandler(authenticationFailureHandler)
//				.and()
//			.exceptionHandling()
//				.accessDeniedHandler((Request,Response, e)->{
//
//				});
		
	}
	
	@Bean
	public PasswordEncoder crePasswordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
}
